package cn.east196.tfx;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import com.jfinal.kit.PropKit;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class FreemakerGenerator {

  private static String UTF8 = "UTF-8";
  private Configuration freemarkerCfg;
  private Template template;
  private File destFile;
  private Map map;

  public FreemakerGenerator(String ftl, String outFile) throws IOException {
	  PropKit.use("config/config.properties");
    String tempDir = System.getProperty("user.home") + PropKit.get("app.templeteDir");
    freemarkerCfg = new Configuration(Configuration.VERSION_2_3_22);
    freemarkerCfg.setDirectoryForTemplateLoading(new File(tempDir));
    freemarkerCfg.setEncoding(Locale.getDefault(), UTF8);
    String group = PropKit.use("application.properties").get("xcurd。group");
    template = freemarkerCfg.getTemplate(group+"/"+ftl, UTF8);
    template.setOutputEncoding(UTF8);
    template.setClassicCompatible(true);
    destFile = new File(outFile);
  }

  public void setData(Map map) {
    this.map = map;
  }

  public void process() throws IOException, TemplateException {
    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(destFile), UTF8));
    template.process(map, out);
    out.flush();
    out.close();
  }
}
